<?php
/**
 * Created by PhpStorm.
 * User: divya
 * Date: 2018/8/1
 * Time: 下午3:10
 */

namespace app\api\service;


use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\TokenExption;
use think\Cache;
use think\Exception;
use think\Request;
use app\api\model\User as UserModel;
class Token
{
    public static function gennerateToken()
    {
        // 32个字符组成一组随机字符串,方法在common.php里
        $randChars = getRandChar(32);
        // 用三组字符串，进行md5加密
         $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
         // salt
         $salt = config('secure.token_salt');
        return md5($randChars.$timestamp.$salt);
    }

    public static function getCurrentTokenVar($key)
    {
        $token = Request::instance()->header('token');
        $vars = Cache::get($token);
        if (!$vars){
            throw new TokenExption();
        }else{
            if (!is_array($vars)){
                $vars = json_decode($vars,true);
            }
            if (array_key_exists($key,$vars)){
                return $vars[$key];
            }else{
                throw  new Exception('尝试获取的Token变量并不存在');
            }
        }
    }
    public static function getCurrentUid()
    {
        $uid = self::getCurrentTokenVar('uid');
        $user = UserModel::get($uid);
        return $uid;
        
    }
    
    // 前置获取规则
    /**
     * 用户和管理员都能
     * */
    public static function needPrimaryScope()
    {
        $scope = self::getCurrentTokenVar('scope');
        if ($scope){
            if ($scope >= ScopeEnum::User){
                return true;
            }else{
                throw new ForbiddenException();
            }
        }else{
            throw new TokenExption();
        }
        
    }
    /**
     *只能用户
     **/
    public static function needExclusiveScope()
    {
        $scope = self::getCurrentTokenVar('scope');
        if ($scope){
            if ($scope == ScopeEnum::User){
                return true;
            }else{
                throw new ForbiddenException();
            }
        }else{
            throw new TokenExption();
        }

    }
    
}